package com.y.report.filter.api;

import com.y.report.entry.ApiEntry;
import com.y.report.exception.ApiExecption;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "apiEntryFilter", urlPatterns = "/api/*")
public class ApiFilter extends OncePerRequestFilter {

    private Logger log = LoggerFactory.getLogger(getClass());

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        try {
            ApiEntry entry = new ApiEntry();
            boolean isEntry = false;
            try {
                isEntry = entry.request();
                if (isEntry) {
                    entry.exec();
                    entry.getApiResponseInfo().setReturnFlag(true);
                    entry.getApiResponseInfo().setMessage("OK");
                }
            } catch (ApiExecption e) {
                log.warn(e.getMessage());
                entry.getApiResponseInfo().setErrorMessage(e.getMessage());
                entry.getApiResponseInfo().setMessage("FAIL");
                isEntry = true;
            } catch (Throwable e) {
                e.printStackTrace();
            } finally {
                if (isEntry) {
                    entry.response();
                    entry.log();
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
            log.warn(e.getMessage());
            filterChain.doFilter(httpServletRequest, httpServletResponse);
        }

    }
}
